import { ref } from 'vue'
import { defineStore } from 'pinia'
import apiClient from '../services/api'

// 定义文档类型
export interface Document {
  id: string
  name: string
  type: string
  size: number
  uploadTime: string
  chunksCount: number
  metadata?: Record<string, any>
  tags?: string[]
}

// 定义文档块类型
export interface DocumentChunk {
  id: string
  documentId: string
  content: string
  score: number
  metadata?: Record<string, any>
}

// 文档管理store
export const useDocumentsStore = defineStore('documents', () => {
  // 状态
  const documents = ref<Document[]>([])
  const selectedDocument = ref<Document | null>(null)
  const documentChunks = ref<DocumentChunk[]>([])
  const isLoading = ref<boolean>(false)
  const uploadProgress = ref<number>(0)
  const isUploading = ref<boolean>(false)
  const searchKeyword = ref<string>('')
  const filters = ref({
    type: '',
    dateRange: null as [string, string] | null
  })
  const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 加载文档列表
  const loadDocuments = async () => {
    isLoading.value = true
    try {
      // 调用API获取文档列表
      const response = await apiClient.get('/v1/documents', {
        params: {
          page: pagination.value.currentPage,
          pageSize: pagination.value.pageSize,
          search: searchKeyword.value,
          ...filters.value
        }
      })
      documents.value = response.data.items || []
      pagination.value.total = response.data.total
    } catch (error) {
      console.error('加载文档列表失败:', error)
      // 可以添加错误处理逻辑
    } finally {
      isLoading.value = false
    }
  }



  // 加载文档详情和文档块
  const loadDocumentDetails = async (documentId: string) => {
    isLoading.value = true
    try {
      // 调用API获取文档详情
      const docResponse = await apiClient.get(`/v1/documents/${documentId}`)
      selectedDocument.value = docResponse.data || null
      
      if (!selectedDocument.value) {
        return
      }
      
      // 调用API获取文档块
      const chunksResponse = await apiClient.get(`/v1/documents/${documentId}/chunks`)
      documentChunks.value = chunksResponse.data.chunks || []
    } catch (error) {
      console.error('加载文档详情失败:', error)
    } finally {
      isLoading.value = false
    }
  }



  // 上传文档
  const uploadDocument = async (file: File, tags: string[] = []) => {
    uploadProgress.value = 0
    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('tags', JSON.stringify(tags))
      
      // 使用axios的onUploadProgress监控上传进度
      const response = await apiClient.post('/v1/documents/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          if (progressEvent.total) {
            uploadProgress.value = Math.round((progressEvent.loaded / progressEvent.total) * 100)
          }
        }
      })
      
      // 上传成功后重新加载文档列表
      await loadDocuments()
      return response.data
    } catch (error) {
      console.error('上传文档失败:', error)
      throw error
    } finally {
      uploadProgress.value = 0
    }
  }



  // 删除文档
  const deleteDocument = async (documentId: string) => {
    try {
      // 调用API删除文档
      await apiClient.delete(`/v1/documents/${documentId}`)
      
      // 从本地数组中删除
      const index = documents.value.findIndex(doc => doc.id === documentId)
      if (index !== -1) {
        documents.value.splice(index, 1)
      }
      
      // 如果删除的是当前选中的文档，清空文档块
      if (selectedDocument.value && selectedDocument.value.id === documentId) {
        selectedDocument.value = null
        documentChunks.value = []
      }
    } catch (error) {
      console.error('删除文档失败:', error)
    }
  }

  // 搜索文档
  const searchDocuments = async (keyword: string) => {
    searchKeyword.value = keyword
    pagination.value.currentPage = 1
    await loadDocuments()
  }

  // 清空搜索
  const clearSearch = async () => {
    searchKeyword.value = ''
    pagination.value.currentPage = 1
    await loadDocuments()
  }

  // 设置过滤器
  const setFilters = async (newFilters: Partial<typeof filters.value>) => {
    filters.value = { ...filters.value, ...newFilters }
    pagination.value.currentPage = 1
    await loadDocuments()
  }

  // 清空过滤器
  const clearFilters = async () => {
    filters.value = {
      type: '',
      dateRange: null
    }
    pagination.value.currentPage = 1
    await loadDocuments()
  }

  // 添加标签
  const addTag = async (documentId: string, tag: string) => {
    try {
      // 调用API添加标签
      await apiClient.post(`/v1/documents/${documentId}/tags`, { tag })
      
      // 从本地数组中更新
      const document = documents.value.find(doc => doc.id === documentId)
      if (document) {
        if (!document.tags) {
          document.tags = []
        }
        if (!document.tags.includes(tag)) {
          document.tags.push(tag)
        }
      }
      
      // 如果修改的是当前选中的文档，同步更新
      if (selectedDocument.value && selectedDocument.value.id === documentId) {
        if (!selectedDocument.value.tags) {
          selectedDocument.value.tags = []
        }
        if (!selectedDocument.value.tags.includes(tag)) {
          selectedDocument.value.tags.push(tag)
        }
      }
    } catch (error) {
      console.error('添加标签失败:', error)
    }
  }

  // 移除标签
  const removeTag = async (documentId: string, tag: string) => {
    try {
      // 调用API移除标签
      await apiClient.delete(`/v1/documents/${documentId}/tags/${encodeURIComponent(tag)}`)
      
      // 从本地数组中更新
      const document = documents.value.find(doc => doc.id === documentId)
      if (document && document.tags) {
        const index = document.tags.indexOf(tag)
        if (index !== -1) {
          document.tags.splice(index, 1)
        }
      }
      
      // 如果修改的是当前选中的文档，同步更新
      if (selectedDocument.value && selectedDocument.value.id === documentId && selectedDocument.value.tags) {
        const index = selectedDocument.value.tags.indexOf(tag)
        if (index !== -1) {
          selectedDocument.value.tags.splice(index, 1)
        }
      }
    } catch (error) {
      console.error('移除标签失败:', error)
    }
  }

  return {
    // 状态
    documents,
    selectedDocument,
    documentChunks,
    isLoading,
    uploadProgress,
    isUploading,
    searchKeyword,
    filters,
    pagination,
    // 方法
    loadDocuments,
    loadDocumentDetails,
    uploadDocument,
    deleteDocument,
    searchDocuments,
    clearSearch,
    setFilters,
    clearFilters,
    addTag,
    removeTag
  }
})